src/roundTo.js
zzmq.dev@gmail.com[dev3]/mathkit[add-roundto-n-decimals-function-rounds] / src / roundTo.js
@ 61ced51e
Download
Ladder Summary
- file Add roundTo function to round numbers to a specified decimal precision with validation and tests
/**
* Rounds a number to a specific number of decimal places.
*
* @param {number} n - The number to round.
* @param {number} decimals - The number of decimal places (non‑negative integer).
* @returns {number|undefined} The rounded number, or undefined for invalid inputs.
*/
export function roundTo(n, decimals) {
if (typeof n !== "number" || !Number.isFinite(n)) return undefined;
if (
typeof decimals !== "number" ||
!Number.isInteger(decimals) ||
decimals < 0
)
return undefined;
const factor = 10 ** decimals;
return Math.round(n * factor) / factor;
}